// 协同任务-岗位列表
<template>
  <div v-show="showPositionList" class="margin-container-list radius-container">
    <div class="border-b pad-10 font-w font-15">
      岗位列表
      <el-button type="primary" size="mini" class="float-r" @click="handleAddPosition">添加岗位</el-button>
    </div>
    <div class="table-container">
      <el-table :data="taskPositionList" @sort-change="sortChange" @selection-change="handleSelectionChange"
                v-loading="listLoading" element-loading-text="加载中"
                style="width: 100%">
        <el-table-column width="135px" label="职位名称" prop="positionName">
        </el-table-column>
        <el-table-column width="135px" label="任务酬金" prop="positionCommission">
        </el-table-column>
        <el-table-column width="135px" label="录用人数" prop="hireNum">
        </el-table-column>
        <el-table-column width="135px" label="工作描述" prop="positionDescription">
        </el-table-column>
        <el-table-column min-width="260px" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="primary" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="taskPositionListQuery.currentPage"
                     :page-sizes="[10, 20, 50, 100]" :page-size="taskPositionListQuery.size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>

    <!-- 岗位弹窗 -->
    <div>
      <el-dialog width="900px" v-el-drag-dialog :visible.sync="positionDialog" center title="岗位详情">
        <div class="border-b font-w font-15">职位信息</div>
        <div class="flex pad-l-30 mar-t-30">
          <el-form ref="form" :model="taskPosition" :rules="positionRules" label-width="100px" class="width-per-80">
            <el-form-item label="岗位名称：" prop="positionName">
              <el-input v-model="taskPosition.positionName"></el-input>
            </el-form-item>
            <el-form-item label="岗位酬金：" prop="positionCommission">
              <el-input v-model="taskPosition.positionCommission" min="0" type="number" placeholder="请输入分配给该岗位的总金额" class="el-input"> <template slot="append">元</template></el-input>
            </el-form-item>
            <el-form-item label="录用人数：" prop="hireNum">
              <el-input  placeholder="请输入该岗位要录用的人数" class="el-input" v-model="taskPosition.hireNum" type="number" :min="1"> <template slot="append">人</template></el-input>
            </el-form-item>
            <el-form-item label="是否可议价：" prop="bargainingFlag">
              <el-radio-group v-model="taskPosition.bargainingFlag" >
                <template v-for="(val, key) in taskDict.bargainingFlag">
                  <el-radio :label="key">{{val}}</el-radio>
                </template>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="工作描述：" prop="positionDescription">
              <el-input type="textarea" v-model="taskPosition.positionDescription" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-form>
          <div class="mar-b-5">
          </div>
        </div>
        <div class="border-b font-w font-15">微客要求</div>
        <div class="pad-20">
          <el-form label-width="120px">
            <el-row>
              <el-form-item label="筛选合作的微客">
                <el-switch v-model="taskPosition.cooperationFlag"></el-switch>
              </el-form-item>
            </el-row>
            <div v-if="taskPosition.cooperationFlag">
              <el-row>
                <el-col :span="12">
                  <el-radio-group v-model="taskPosition.cooperationFilterType">
                    <template v-for="(val, key) in taskDict.cooperationFilterType">
                      <el-radio :label="key">{{val}}</el-radio>
                    </template>
                  </el-radio-group>
                </el-col>
              </el-row>
              <el-row>
                <el-form-item label-width="150px" label="推送范围：" v-if="taskPosition.cooperationFilterType==1">
                  <el-radio-group v-model="taskPosition.filterDirectionType" >
                    <template v-for="(val, key) in taskDict.filterDirectionType">
                      <el-radio :label="key">{{val}}</el-radio>
                    </template>
                  </el-radio-group>
                </el-form-item>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="150px" label="选择推送：" v-if="taskPosition.cooperationFilterType==2">
                    <el-input type="textarea" :rows="5" placeholder=""  v-model="taskPosition.selectMemberNames" class="width-per-80" />
                    <el-button type="primary" size="mini" @click="memberDialog = true">选择微客</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <el-row>
              <el-form-item label="是否招募新微客">
                <el-switch v-model="taskPosition.recruitFlag"></el-switch>
              </el-form-item>
            </el-row>
            <div v-if="taskPosition.recruitFlag">
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="150px">
                    <el-input type="textarea" :rows="3" placeholder=""  v-model="taskPosition.selectRecruiterNames" class="width-per-80" />
                    <el-button type="primary" size="mini" @click="recruiterDialog = true">选择招募员</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="positionDialog=!positionDialog">取消</el-button>
          <el-button type="primary" @click="savePosition">确定</el-button>
        </div>
      </el-dialog>

      <!-- 选择招募员弹窗 -->
      <el-dialog title="选择招募员帮您招募新微客" width="700px"  v-el-drag-dialog :visible.sync="recruiterDialog" center >
        <div class="flex pad-l-30 mar-t-30">
          <div class="mar-l-5">
            <el-transfer
              style="text-align: left; display: inline-block"
              v-model="taskPosition.recruiterIds"
              filterable
              :left-default-checked="[]"
              :right-default-checked="taskPosition.recruiterIds"
              :titles="['我的招募员', '已选择']"
              :button-texts="['到左边', '到右边']"
              :format="{noChecked: '${total}', hasChecked: '${checked}/${total}'}"
              :data="recruiterData">
            </el-transfer>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="recruiterDialog=!recruiterDialog">取消</el-button>
          <el-button type="primary" @click="handleRecruiterChange">确定</el-button>
        </div>
      </el-dialog>

      <!-- 选择微客弹窗 -->
      <el-dialog title="选择定向推送的微客" width="700px"  v-el-drag-dialog :visible.sync="memberDialog" center >
        <div class="flex pad-l-30 mar-t-30">
          <div class="mar-l-5">
            <el-transfer
              style="text-align: left; display: inline-block"
              v-model="taskPosition.memberIds"
              filterable
              :left-default-checked="[]"
              :right-default-checked="taskPosition.memberIds"
              :titles="['我的招募员', '已选择']"
              :button-texts="['到左边', '到右边']"
              :format="{noChecked: '${total}', hasChecked: '${checked}/${total}'}"
              :data="memberData">
            </el-transfer>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="memberDialog=!memberDialog">取消</el-button>
          <el-button type="primary" @click="handleMemberChange">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>

</template>

<style scoped>
  .el-dialog--center .el-dialog__body {
    padding: 0px 25px 30px;
  }

</style>

<script>
  import { listRecruiterList, listPushMemberList } from '@/api/project/taskInfo'
  import { getDictByGroupName } from '@/api/common/common'
  import elDragDialog from '@/directive/el-dragDialog'
  // 任务岗位列表
  export default {
    props: {
      //  任务状态状态 10:未发布 20:待托管 30：平台审核中 40：报名中 50：待签约 60进行中 70已完成 80 已中止
      taskStatus: {
        type: String
      }
    },
    data() {
      return {
        showPositionList: false,
        taskId: '',
        taskPositionList: [],
        total: null,
        listLoading: false,
        multipleSelection: [],
        taskPositionListQuery: {
          currentPage: 1,
          size: 10,
          taskId: ''
        },
        defaultTaskPosition: {
          positionId: '',
          taskId: '',
          positionName: '',
          hireNum: '',
          positionCommission: '',
          positionDescription: '',
          enrolmentNum: '',
          hiredNum: '',
          signingNum: '',
          cooperationFlag: true,
          cooperationFilterType: '1',
          filterDirectionType: '1',
          recruitFlag: true,
          bargainingFlag: '0',
          recruiterIds: [],
          memberIds: [],
          selectMemberNames: '',
          selectRecruiterNames: ''
        },
        taskPosition: {},
        recruiterDialog: false,
        recruiterData: [],
        recruiterMap: {},
        memberDialog: false,
        memberData: [],
        memberMap: {},
        positionDialog: false,
        categoryExperiences: [],
        categorySkills: [],
        taskDict: {},
        positionRules: {
          positionName: [
            { required: true, message: '请填写岗位名称', trigger: 'blur' }
          ],
          positionCommission: [
            { required: true, message: '岗位酬金不能为空', trigger: 'blur' }
          ],
          hireNum: [
            { required: true, message: '录用人数不能为空', trigger: 'blur' }
          ]
        },
        positionIndex: 1
      }
    },
    directives: {
      // 拖动窗口
      elDragDialog
    },
    // 过滤器
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    },
    // 初始化页面
    created() {
      this.busListener()
      this.taskPosition = { ...this.defaultTaskPosition }
      this.initDict()
      this.initRecruiterList()
      this.initPushMemberList()
    },
    methods: {
      busListener() {
        const that = this
        this.$bus.$on('project.task.edit.taskType', function(taskType) {
          that.showPositionList = taskType * 1 === 2
        })
        this.$bus.$on('project.task.edit.taskData', function(taskData) {
          const taskType = taskData.taskType + ''
          if (taskType !== '2') {
            return
          }
          that.taskPositionList = taskData.positionList
          that.taskPositionList.forEach(position => {
            position.rowId = that.positionIndex++
          })
          that.total = that.taskPositionList.length
        })
      },
      // 初始化任务相关数据字典
      initDict() {
        getDictByGroupName('TaskInfoDTO').then(response => {
          this.taskDict = response.data
        })
      },
      // 加载招募员
      initRecruiterList() {
        const enterpriseId = this.getEnterpriseId()
        listRecruiterList(enterpriseId).then(response => {
          if (response.isError) {
            return
          }
          const recruiterList = response.data
          if (recruiterList && recruiterList.length > 0) {
            recruiterList.forEach(recruiter => {
              this.recruiterData.push({
                key: recruiter.recruiterId,
                label: recruiter.realname
              })
              this.recruiterMap[recruiter.recruiterId] = recruiter.realname
            })
          }
        })
      },
      // 加载微客
      initPushMemberList() {
        listPushMemberList(this.getEnterpriseId()).then(response => {
          if (response.isError) {
            return
          }
          const memberList = response.data
          if (memberList && memberList.length > 0) {
            memberList.forEach(member => {
              this.memberData.push({
                key: member.memberId,
                label: member.nickname
              })
              this.memberMap[member.memberId] = member.nickname
            })
          }
        })
      },
      // 保存岗位信息
      savePosition() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return
          }
          // 启用定向选择微客时，微客列表必填
          if (this.taskPosition.cooperationFlag && this.taskPosition.cooperationFilterType * 1 === 2) {
            if (!this.taskPosition.memberIds || this.taskPosition.memberIds.length === 0) {
              this.$message({
                type: 'warning',
                message: '微客列表不能为空'
              })
              return
            }
          }
          // 启用是否招募新微客，招募员列表必填
          if (this.taskPosition.recruitFlag) {
            if (!this.taskPosition.recruiterIds || this.taskPosition.recruiterIds.length === 0) {
              this.$message({
                type: 'warning',
                message: '招募员列表不能为空'
              })
              return
            }
          }
          this.taskPosition.positionCommission = (this.taskPosition.positionCommission * 1).toFixed(2)
          const position = { ...this.taskPosition }
          position.memberRequire = this.getMemberRequire()
          position.memberDirections = this.getMemberDirections()
          position.recruits = this.getRecruits()
          if (!position.rowId) {
            position.rowId = this.positionIndex++
            this.taskPositionList.push(position)
          } else {
            const index = this.taskPositionList.findIndex(p => p.rowId === position.rowId)
            Object.assign(this.taskPositionList[index], position)
          }
          this.taskPosition = { ...this.defaultTaskPosition }
          this.positionDialog = false
        })
      },
      // 列表排序
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'createTime') {
          if (order === 'ascending') {
            this.taskPositionListQuery.ascs = 'createTime'
            this.taskPositionListQuery.descs = ''
          } else {
            this.taskPositionListQuery.ascs = ''
            this.taskPositionListQuery.descs = 'createTime'
          }
        }
        this.initTaskPositionList()
      },
      handleSearch() {
        this.taskPositionListQuery.currentPage = 1
        this.initTaskPositionList()
      },
      handleSizeChange(val) {
        this.taskPositionListQuery.size = val
        this.initTaskPositionList()
      },
      handleCurrentChange(val) {
        this.taskPositionListQuery.currentPage = val
        this.initTaskPositionList()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 添加
      handleCreate() {
      },
      // 编辑
      handleUpdate(row) {
        const position = this.taskPositionList[this.taskPositionList.findIndex(position => position.rowId === row.rowId)]
        this.taskPosition = { ...position }
        this.taskPosition.cooperationFlag = this.taskPosition.memberRequire.cooperationFlag === 1
        const cooperationFilterType = this.taskPosition.memberRequire.cooperationFilterType
        this.taskPosition.cooperationFilterType = !cooperationFilterType ? '1' : cooperationFilterType + ''
        const filterDirectionType = this.taskPosition.memberRequire.filterDirectionType
        this.taskPosition.filterDirectionType = !filterDirectionType ? '1' : filterDirectionType + ''
        this.taskPosition.recruitFlag = this.taskPosition.memberRequire.recruitFlag === 1
        this.taskPosition.bargainingFlag = this.taskPosition.bargainingFlag + ''
        this.taskPosition.recruiterIds = []
        this.taskPosition.selectRecruiterNames = ''
        if (this.taskPosition.recruitFlag) {
          const recruiterNamesArray = []
          this.taskPosition.recruits.forEach(recruiter => {
            this.taskPosition.recruiterIds.push(recruiter.recruiterId)
            recruiterNamesArray.push(this.recruiterMap[recruiter.recruiterId])
          })
          this.taskPosition.selectRecruiterNames = recruiterNamesArray.join(';')
        }
        this.taskPosition.memberIds = []
        this.taskPosition.selectMemberNames = ''
        if (this.taskPosition.cooperationFlag && this.taskPosition.cooperationFilterType * 1 === 2) {
          const memberNamesArray = []
          this.taskPosition.memberDirections.forEach(member => {
            this.taskPosition.memberIds.push(member.memberId)
            memberNamesArray.push(this.memberMap[member.memberId])
          })
          this.taskPosition.selectMemberNames = memberNamesArray.join(';')
        }
        this.positionDialog = true
      },
      // 删除
      handleDelete(row) {
        this.$confirm('此操作将删除岗位, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.taskPositionList.splice(this.taskPositionList.findIndex(position => position.rowId === row.rowId), 1)
        }).catch(() => {
        })
      },
      // 添加岗位
      handleAddPosition() {
        this.positionDialog = true
      },
      // 选择招募员
      handleRecruiterChange() {
        const recruiterNamesArray = []
        this.taskPosition.recruiterIds.forEach(recruiterId => {
          recruiterNamesArray.push(this.recruiterMap[recruiterId])
        })
        this.taskPosition.selectRecruiterNames = recruiterNamesArray.join(';')
        this.recruiterDialog = false
      },
      // 选择微客
      handleMemberChange() {
        const memberNamesArray = []
        this.taskPosition.memberIds.forEach(memberId => {
          memberNamesArray.push(this.memberMap[memberId])
        })
        this.taskPosition.selectMemberNames = memberNamesArray.join(';')
        this.memberDialog = false
      },
      // 获取所有岗位的录用人数
      getHireNum() {
        let hireNum = 0
        this.taskPositionList.forEach(taskPosition => {
          hireNum += taskPosition.hireNum * 1
        })
        return hireNum
      },
      // 微客要求
      getMemberRequire() {
        let filterDirectionType = ''
        if (this.taskPosition.cooperationFlag && this.taskPosition.cooperationFilterType * 1 === 1) {
          filterDirectionType = this.taskPosition.filterDirectionType * 1
        }
        return {
          cooperationFlag: this.taskPosition.cooperationFlag ? 1 : 0,
          cooperationFilterType: this.taskPosition.cooperationFlag ? this.taskPosition.cooperationFilterType * 1 : '',
          filterDirectionType: filterDirectionType,
          recruitFlag: this.taskPosition.recruitFlag ? 1 : 0
        }
      },
      // 定向选择
      getMemberDirections() {
        const memberDirections = []
        if (this.taskPosition.cooperationFlag && this.taskPosition.cooperationFilterType * 1 === 2) {
          if (this.taskPosition.memberIds && this.taskPosition.memberIds.length > 0) {
            this.taskPosition.memberIds.forEach(memberId => {
              memberDirections.push({
                memberId: memberId
              })
            })
          }
        }
        return memberDirections
      },
      // 招募新微客
      getRecruits() {
        const recruiters = []
        if (this.taskPosition.recruitFlag) {
          if (this.taskPosition.recruiterIds && this.taskPosition.recruiterIds.length > 0) {
            this.taskPosition.recruiterIds.forEach(recruiterId => {
              recruiters.push({
                recruiterId: recruiterId
              })
            })
          }
        }
        return recruiters
      }
    }
  }
</script>
